package com.sosee.cgfw.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.BrandUperData;
import com.sosee.cgfw.entity.Data;
import com.sosee.cgfw.entity.JsonData;
import com.sosee.cgfw.entity.PiaoJia;
import com.sosee.cgfw.entity.PiaoJiaJson;
import com.sosee.cgfw.gaodemap.NewTestActivity;
import com.sosee.cgfw.myview.PickerView;
import com.sosee.cgfw.receiver.AlarmReceiver;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Thinkpad on 2016/2/1.
 * 活动日程详情页
 */
public class ScheduleDetailActivity extends Activity implements View.OnClickListener {
    private ImageView ig_logo;//详情logo
    private TextView tv_info;//标题
    private TextView tv_company;//举办方
    private TextView tv_company_e;
    private TextView tv_date;//日期
    private TextView tv_time;//时间
    private TextView tv_address;//地址
    private TextView tv_start_time;//开场时间
    private TextView tv_address_e;
    private BitmapUtils bitmapUtils;
    private ImageView ig_shoucang;//收藏按钮
    private ImageView ig_daohang;//导航按钮
    private ImageView ig_tixing;//提醒按钮
    private ImageView ig_shenqing;//申请按钮
    private String schedule_id;//活动id；
    private HttpUtils httpUtils;
    private RelativeLayout rl_shenqing;//申请菜单
    private TextView ig_queren;//确认申请
    private TextView ig_quxiao;//取消
    private RelativeLayout ll_time;//事件选择器
    private TextView tv_shoucang_able;//是否已收藏
    private TextView tv_tixing;//是否已设置提醒

    private PickerView pv_day;//日期
    private PickerView pv_hour;//小时
    private PickerView pv_min;//分钟
    private PickerView pv_am;//上下午
    private List<String> day_list;//日期集合
    private List<String> hour_list;//小时 集合
    private List<String> time_list;//分集合
    private List<String> am_list;//
    private RelativeLayout rl_shenqing_pop;//申请弹框
    public static int BUCHANG;

    private SharedPreferences sp=null;
    private int remind=0;
    private String day_use;
    private String min;
    private String hour;
    private boolean isPm;
    private Calendar cal;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule_detail);
        initView();
        initData();
        setSelect();
        initTimerSelectorData();
        initTimerSelector();
    }


    public void setSelect(){

            String date=data.getData().getStart_date();
            String[] da=date.split("-");
        int year=Integer.parseInt(da[0]);
        int mon=Integer.parseInt(da[1]);
        int day=Integer.parseInt(da[2]);
        day_use=Utils.getDate(year,mon,day);
            cal=Calendar.getInstance();
            cal.set(year,mon-1,day);
            LogUtils.log_E("测试日期==="+day_use);
            String time= data.getData().getStart_time();
            String[] t=time.split(":");
            int t1=Integer.parseInt(t[0]);
            min=t[1];
            if(t1>12){
                isPm=true;
            }
            hour=t1%12+"";



    }

    public void initTimerSelector() {
        //测试坐标补偿
        buCang();
        pv_day = (PickerView) findViewById(R.id.pv_day);
        pv_day.setmBucang(BUCHANG);
        pv_day.setData(day_list);
        pv_day.setSelected(10);
        pv_hour = (PickerView) findViewById(R.id.pv_hour);
        pv_hour.setData(hour_list);
        pv_hour.setSelected(6);
        pv_min = (PickerView) findViewById(R.id.pv_min);
        pv_min.setData(time_list);
        pv_min.setSelected(10);
        pv_am = (PickerView) findViewById(R.id.pv_am);
        pv_am.setData(am_list);
        if(isPm){
            pv_am.setSelected(1);
        }else{
            pv_am.setSelected(0);
        }


    }

    public void initTimerSelectorData() {
        hour_list = new ArrayList<String>();
        for (int i = 1; i < 13; i++) {
            hour_list.add(i + "时");
        }
        time_list = new ArrayList<String>();
        for (int i = 0; i < 60; i++) {
            if (i < 10) {
                time_list.add("0" + i+"分");
            } else {
                time_list.add(i + "分");
            }
        }
        hour_list.add(6,hour+"时");
        time_list.add(10, min + "分");

        //待优化处理
        day_list = Utils.getTime();
        day_list.add(10, day_use);
        Utils.dayList.add(10, cal);
        am_list = new ArrayList<String>();
        am_list.add("AM");
        am_list.add("PM");
    }





    public void initView() {
        httpUtils = new HttpUtils();
        ig_logo = (ImageView) findViewById(R.id.ig_logo);
        tv_info = (TextView) findViewById(R.id.tv_info);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_address_e = (TextView) findViewById(R.id.tv_address_e);
        tv_company = (TextView) findViewById(R.id.tv_compan);
        tv_company_e = (TextView) findViewById(R.id.tv_company_e);
        tv_date = (TextView) findViewById(R.id.tv_date);
        tv_time = (TextView) findViewById(R.id.tv_start_time);
        tv_start_time= (TextView) findViewById(R.id.tv_start);
        ig_shoucang = (ImageView) findViewById(R.id.ig_shoucang);


        ig_daohang = (ImageView) findViewById(R.id.ig_daohang);
        ig_shenqing = (ImageView) findViewById(R.id.ig_shenqing);
        ig_tixing = (ImageView) findViewById(R.id.ig_tixing);
        setOnClick();

        rl_shenqing = (RelativeLayout) findViewById(R.id.rl_shenqing);
        ig_queren = (TextView) findViewById(R.id.ig_queren);

        ll_time = (RelativeLayout) findViewById(R.id.ll_time);
        rl_shenqing_pop = (RelativeLayout) findViewById(R.id.rl_shengqing);

        tv_shoucang_able= (TextView) findViewById(R.id.tv_shoucang_able);
        tv_tixing= (TextView) findViewById(R.id.tv_tixing);


    }

    //申请点击事件
    public void shenQing(View view) {
        int id = view.getId();
        switch (id) {
            //确认申请
            case R.id.ig_queren:
                apply();
                break;
            //取消
            case R.id.ig_quxiao:
                rl_shenqing.setVisibility(View.GONE);
                break;
        }

        rl_shenqing_pop.setVisibility(View.INVISIBLE);

    }

    //申请活动
    public void apply() {
        LogUtils.log_E("申请id"+schedule_id);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.URL_APPLY +Constans.userID+ "&showID=" + schedule_id, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject obj = new JSONObject(responseInfo.result);
                    String msg = obj.getString("msg");
                    String status = obj.getString("status");
                    LogUtils.log_E(msg);
                    if ("success".equals(status)) {
                        if(msg.trim().equals("审核通过")){
                            tv_shoucang_able.setText("已获取");
                        }else if(msg.trim().equals("等待审核")||msg.trim().equals("申请成功, 请等待审批完成")){
                            tv_shoucang_able.setText("待审核");
                        }else{
                            tv_shoucang_able.setText("未通过");
                        }
                    } else {
                        Utils.showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast(getString(R.string.apply_failed));
            }
        });

    }

    //为按钮设置监听事件
    public void setOnClick() {
        ig_shoucang.setOnClickListener(this);
        ig_daohang.setOnClickListener(this);
        ig_shenqing.setOnClickListener(this);
        ig_tixing.setOnClickListener(this);
    }

    //判断邀请函申请状态
    public void apply_status(final String id){
        LogUtils.log_E("测试是否判断秀场申请状态");
        //待实现
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.PIAO_URL + Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    LogUtils.log_E("申请状态json" + responseInfo.result);
                    String status = jsonObject.getString("status");
                    if ("success".equals(status)) {
                        PiaoJiaJson pjson = com.alibaba.fastjson.JSONObject.parseObject(responseInfo.result, PiaoJiaJson.class);
                        List<PiaoJia> list = pjson.getResult();
                        if (list != null) {
                        } else {
                            Utils.showToast("解析json出错");
                        }
                        initUI(list, id);
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtils.log_E("测试是否出错json：" + e.getMessage());
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void initUI(List<PiaoJia> list,String id) {
        LogUtils.log_E("detail id" + id);
        for (PiaoJia p:list){
            Data data= null;
            String show=p.getData().getShow().get(0);
            LogUtils.log_E("测试show::::"+show);
            if(show.length()>10){
                try {

                    org.json.JSONArray arr=new org.json.JSONArray(show);
                    JSONObject ob=arr.getJSONObject(0);
                    JSONObject obj=ob.getJSONObject("data");
                    data=new Data();
                    data= com.alibaba.fastjson.JSONObject.parseObject(obj.toString(),Data.class);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                LogUtils.log_E("ceshi id"+data.getID()+data.getAddressA());
                if(id.equals(data.getID())){
                    LogUtils.log_E("测试判断"+p.getData().getStatus());
                    switch (Integer.parseInt(p.getData().getStatus())){
                        case 0:
                            tv_shoucang_able.setText("未申请");
                            break;
                        case 1:
                            tv_shoucang_able.setText("已获取");
                            break;
                        case 4:
                            tv_shoucang_able.setText("已获取");
                            break;
                        case 5:
                            tv_shoucang_able.setText("待审核");
                            break;
                        case 6:
                            tv_shoucang_able.setText("未通过");
                            break;
                        case 7:
                            tv_shoucang_able.setText("转赠中");

                    }
                }
            }
        }
        if(tv_shoucang_able.getText().length()<2){
            tv_shoucang_able.setText("未申请");
        }
    }


    JsonData data;
    public void initData() {
        sp=getSharedPreferences(Constans.ALARM, MODE_PRIVATE);
        sp1=getSharedPreferences(Constans.REMIND_TIME,MODE_PRIVATE);
        bitmapUtils = new BitmapUtils(this);
        //获取活动数据
        data = (JsonData) getIntent().getSerializableExtra("detail");
        String info = data.getData().getTitle();
        String company = data.getData().getUndertake();
        String company_e = data.getData().getUndertake_e();
        String date = data.getData().getStart_date();
        String time = data.getData().getStart_time();
        String address = data.getData().getAddressA();
        address_query = data.getData().getAddressB();
        String address_e = data.getData().getAddressA_e();
        String start=data.getData().getEnter_time();//入场时间
        String id = data.getData().getID();
        String oid=sp.getString(Constans.ALARM, "");
        List<String> tem=Utils.stringToList(oid,",");
        if(tem.contains(id)){
            tv_tixing.setText(sp1.getString(id,""));
        }else{
            tv_tixing.setText("未设置提醒");
        }
        //判断申请状态
        apply_status(id);


        schedule_id = id;
        //判断是否已收藏 确定收藏按钮图标
        if (Utils.list_shoucang.contains(id)) {
            ig_shoucang.setImageResource(R.drawable.yishoucang);
        } else {
            ig_shoucang.setImageResource(R.drawable.shoucang);
        }
        tv_info.setText(info);
        //以下位置调整  命名有问题
        tv_address.setText(company);
        tv_address_e.setText(company_e);
        tv_company.setText(address);
        tv_company_e.setText(address_e);
        tv_date.setText(date);
        tv_time.setText(start);
        tv_start_time.setText(time);
        String key=getIntent().getStringExtra("key");
        List<BrandUperData> blist = data.getData().getBrand();
        if (blist != null && blist.size() > 0) {
                String pic = blist.get(0).getData().getPic().get(0);
                if (pic != null && !pic.equals("")) {
                    bitmapUtils.display(ig_logo, Constans.URL_LOGO_BASE + pic+"logo.jpg");
                }
        } else {
//            LogUtils.log_E("null");
            if(key!=null&&key.length()>2){
                bitmapUtils.display(ig_logo, Constans.URL_LOGO_BASE + key+"logo.jpg");
            }
        }
        remind=getIntent().getIntExtra("remind",0);
        if(remind==1){
            rl_shenqing_pop.setVisibility(View.GONE);
            ll_time.setVisibility(View.VISIBLE);
        }
    }

    //收藏、导航、提醒、申请按钮的点击事件
    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            //收藏
            case R.id.ig_shoucang:
                if(Constans.userID==null||Constans.userID.trim().equals("")){
                    startActivity(new Intent(this,LoginActivity.class));
                }else{
                    httpUtils.send(HttpRequest.HttpMethod.GET, Constans.URL_SHOUCANG +Constans.userID+ "&showID=" + schedule_id, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            String json = responseInfo.result;
                            String status = null;
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                status = jsonObject.getString("status");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } finally {
                                if ("success".equals(status)) {
                                    if (Utils.list_shoucang.contains(schedule_id)) {
                                        Utils.list_shoucang.remove(schedule_id);
                                        ig_shoucang.setImageResource(R.drawable.shoucang);
                                        Utils.showToast(getString(R.string.shoucang_cancle_success));
                                    } else {
                                        Utils.showToast(getString(R.string.shoucang_success));
                                        Utils.list_shoucang.add(schedule_id);
                                        ig_shoucang.setImageResource(R.drawable.yishoucang);
                                    }

                                } else {
                                    if (Utils.list_shoucang.contains(schedule_id)) {
                                        Utils.showToast(getString(R.string.shoucang_cancle_failed));
                                    } else {
                                        Utils.showToast(getString(R.string.shoucang_failed));
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            if (Utils.list_shoucang.contains(schedule_id)) {
                                Utils.showToast(getString(R.string.shoucang_cancle_failed));
                            } else {
                                Utils.showToast(getString(R.string.shoucang_failed));
                            }
                        }
                    });
                };

                break;
            //导航
            case R.id.ig_daohang:
                testSearch();
                break;
            //提醒
            case R.id.ig_tixing:
                int vis=ll_time.getVisibility();
                if(vis==View.VISIBLE){
                    rl_shenqing_pop.setVisibility(View.GONE);
                    ll_time.setVisibility(View.GONE);
                }else{
                    rl_shenqing_pop.setVisibility(View.GONE);
                    ll_time.setVisibility(View.VISIBLE);
                }

                break;
            //申请
            case R.id.ig_shenqing:
                if(Constans.userID==null||Constans.userID.trim().equals("")){
                    startActivity(new Intent(this, LoginActivity.class));
                }else{
                    int visable=rl_shenqing_pop.getVisibility();
                    if(visable==View.VISIBLE){
                        rl_shenqing_pop.setVisibility(View.GONE);
                        rl_shenqing.setVisibility(View.GONE);
                    }else{
                        rl_shenqing_pop.setVisibility(View.VISIBLE);
                        rl_shenqing.setVisibility(View.VISIBLE);
                        ll_time.setVisibility(View.GONE);
                    }
                }
                break;
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void buCang() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int height = metric.heightPixels;   // 屏幕高度（像素）
        int y = height / 2;
        int[] sc = new int[2];
        ll_time.getLocationInWindow(sc);
        int y1 = sc[1] + ll_time.getHeight() / 2;
        BUCHANG = y1 - y;

    }

    private int from = 0;//标记 来自哪个页面  0表示活动日程页面 1品牌详情页面  2智能助理页面
    public void click(View view) {
        rl_shenqing.setVisibility(View.GONE);
    }
    //处理返回事件
    @Override
    public void onBackPressed() {
        from = getIntent().getIntExtra("from", 0);
        switch (from) {
            case 0:
                startActivity(new Intent(this, ScheduleActivity.class));
                break;
            case 1:
                break;
            case 2:
                startActivity(new Intent(this,AssistantActivity.class));
                break;
        }
        finish();
    }
    //地理反编码
    List<GeocodeAddress> glist = new ArrayList<GeocodeAddress>();

    public void testSearch() {

        GeocodeSearch mSearch = new GeocodeSearch(this);
        mSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                glist = geocodeResult.getGeocodeAddressList();
                //未搜索到结果 处理
                if (glist != null) {
                    LogUtils.log_E("glist==0"+i);
                } else {
                    Utils.showToast("网络未连接");
                    return;
                }
                NaviLatLng end = null;
                if (glist.get(0).getLatLonPoint() == null) {
                } else {
                }
                end = new NaviLatLng(glist.get(0).getLatLonPoint().getLatitude(), glist.get(0).getLatLonPoint().getLongitude());
                Utils.eNlat = end;
                LogUtils.log_E(end.getLatitude() + ":" + end.getLongitude());
                Intent gpsNaviIntent = new Intent(ScheduleDetailActivity.this, NewTestActivity.class);
                gpsNaviIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                gpsNaviIntent.putExtra("address", address_query);
                startActivity(gpsNaviIntent);
                finish();

            }
        });


        mSearch.getFromLocationNameAsyn(new GeocodeQuery(address_query, "北京"));
        LogUtils.log_E("测试导航数据:"+address_query);
    }

    private String address_query;


    //返回事件
    public void back(View view) {
        from = getIntent().getIntExtra("from", 0);
        switch (from) {
            case 0:
                startActivity(new Intent(this, ScheduleActivity.class));
                break;
            case 1:
                break;
            case 2:
                startActivity(new Intent(this,AssistantActivity.class));
                break;
        }
        finish();
    }

    //设置提醒事件
    public void setRemind(View view) {
        ll_time.setVisibility(View.GONE);
        int id = view.getId();
        switch (id) {
            case R.id.tim_cancle:
                setShare(schedule_id,true);
                cancleRreminTimer();
                break;
            case R.id.tim_set:
                setShare(schedule_id,false);
                setRemindTimer();
                break;
        }
    }


    private PendingIntent sender;
    private AlarmManager alarm;

    //设置提前通知
    private SharedPreferences sp1;
    public void setRemindTimer() {

        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("detail",data);
        intent.setAction("short");
        sender =
                PendingIntent.getBroadcast(this, 0, intent, 0);
        //设定一个五秒后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        Calendar cal=Utils.dayList.get(pv_day.getmCurrentSelected());
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), pv_hour.getmCurrentSelected(), pv_min.getmCurrentSelected());
        calendar.add(Calendar.SECOND, 10);
        long t1=cal.getTimeInMillis();
        long t2=calendar.getTimeInMillis();
        LogUtils.log_E("测试时间差距"+(t1-t2));

        alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
        Utils.showToast("设置提醒成功");
        String day=day_list.get(pv_day.getmCurrentSelected());
        String hou=hour_list.get(pv_hour.getmCurrentSelected());
        String min=time_list.get(pv_min.getmCurrentSelected());
        tv_tixing.setText(day+hou+":"+min);
        sp1.edit().putString(schedule_id,day+hou+":"+min).commit();
    }

    public void cancleRreminTimer() {
//        if (alarm != null) {
//            alarm.cancel(sender);
//            Utils.showToast("取消提醒成功");
//        } else {
//            Utils.showToast("您未设置提醒");
//        }

        Utils.showToast("取消提醒成功");
        tv_tixing.setText("未设置提醒");
    }

    public void setShare(String id,boolean isRemove){
        String oid=sp.getString(Constans.ALARM, "");
        List<String> temList =Utils.stringToList(oid, ",");

        if(isRemove){
            if(temList.contains(id)){
                temList.remove(id);
            }
        }else{
            temList.add(id);
        }
        oid=Utils.listToString(temList,",");
        SharedPreferences.Editor ed=sp.edit();
        LogUtils.log_E("设置提醒字符串："+oid);
        ed.putString(Constans.ALARM, oid);
        ed.commit();

    }

    //播放系统铃声
    public  void alarm(){
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(this, RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mp.prepare();
            mp.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
